<?php
namespace app\api\controller;

use app\api\Base;
use think\Config;
use think\Db;
use think\request;
use baseutils\BaseUtil; # 验证类
use com\gdl\newagk\interfaces\AdminQbankServiceClient;
use com\gdl\newagk\dataobject\adminqbank\QbankDTO; 

/**
 * 题库接口
 * @author tc 2018/05/07
 */

class Adminqbank extends Base
{
 	/** 
 	 *  题库列表
     *  @param  admin_reg or plaformId
 	 *  @return JSON [description] 400失败 200成功
 	 */
	public function qbankList() 
    {
        // header("Access-Control-Allow-Origin:*"); 
        // header("Access-Control-Allow-Headers:content-type"); 
        // header("Access-Control-Request-Method:GET,POST"); 
        // if(strtoupper($_SERVER['REQUEST_METHOD'])== 'OPTIONS'){ 
        //  exit; 
        // } 
    	$msg = ['code'=>400, 'msg'=>'暂无数据', 'data'=>[],'count'=>0];
        $plaformId = $this->request->param('plaformId')>=0 ? $this->request->param('plaformId') : 0; # 平台id
        $liekName = $this->request->param('name') ? $this->request->param('name') : ""; #题库名称
        $plaformChildId = $this->request->param('plaformChildId') ? $this->request->param('plaformChildId') : 0; # 赛选平台
        $sharingPlaform = $this->request->param('sharingPlaform') ? $this->request->param('sharingPlaform') : ""; # 共享题库来源
        $qbankType = $this->request->param('qbankType')>=0 ? $this->request->param('qbankType') : ""; # 题库类型 0：自建题库 1:分享题库
        $status = $this->request->param('status')>=0 ? $this->request->param('status') : ""; # 题库状态0:禁用 1：启用 2：平台已禁用 总平台禁用为平台已禁用'
        $sharing  = $this->request->param('sharing')>=0 ? $this->request->param('sharing') : "";#是否给下级共享题库 0不共享 1共享 2平台已禁用'
        $adminId = $this->request->param('adminId') ? $this->request->param('adminId') : ""; # 带入管理员is
        $offset = $this->request->param('offset') ? $this->request->param('offset') : 0; # 分页
        $num = $this->request->param('num') ? $this->request->param('num') : 10; # 条数
        // if(empty($this->request->post())){
        //     $msg['msg'] = "请选择相关平台";
        //     return json_encode($msg);
        // }
        #利用此条获取题库列表
        $getAllList = $this->request->param('getBankList') ? $this->request->param('getBankList') : ''; 
        // var_dump($this->request->param());exit;
        # 获取admin_reg one:获取单个平台admin_reg child:获取当前平台和子平台admin_reg all:超级管理员获取所有平台admin_reg
        $plaformId = $plaformChildId ? $plaformChildId : $plaformId;
        if($plaformId==0){
            $adminReg = getApiAdminReg($plaformId,'all');     
        }else{
            $adminReg = getApiAdminReg($plaformId,'child'); 
        }
        //$adminReg = getApiAdminReg($plaformId,'all');     
        try { 
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $AdminQbankService = new AdminQbankServiceClient(NULL);
            \ApiClient::build($AdminQbankService);
            $QbankDO = new QbankDTO(); 
            // var_dump($AdminQbankService);exit;
            
            $QbankDO->offset = $offset;
            $QbankDO->num = $num; 

            # 总平台查看所有 子平台查看本平台
            $where = " agk_qbank.isdelete = 0 and agk_qbank.admin_reg in ('{$adminReg}') ";
            # 模糊查询
            if($liekName){
                //$QbankDO->update=$liekName; 
                $where .=" and agk_qbank.name like '%".trim($liekName)."%' ";
            }
            # 题库类型 分享
            if($qbankType==1){
                $where .=" and  agk_qbank.qbankPid <>0 ";
            }
            # 自建
            if($qbankType==0 && $qbankType!=''){
                $where .=" and  agk_qbank.qbankPid=0 ";
            }

            # 题库状态赛选
            // if(isset($status) && $status>=0 && $status!=''){
            //     $where .= " and agk_qbank.status = ".$status;
            // }
            if($status==1){
                $where .= " and agk_qbank.status = 1";
            }
            if($status==2){
                $where .= " and agk_qbank.status = 0";
            }
            if($status==3){
                $where .= " and agk_qbank.status = 2";
            }

            # 是否为云题库
            if(isset($sharing) && $sharing>=0 && $sharing!=''){
                $where .= " and agk_qbank.issharing = ".$sharing;   
            }

            # 分享题库来源平台
            if($sharingPlaform && !empty($sharingPlaform)){
                // todo
            }
            # 查询该题库是否属于该管理员表
            if($adminId && $adminId!=1){
                $where .=" and uc.adminUserId=".$adminId;
            }

            if($getAllList=="all"){
                $QbankDO->update = $getAllList;     
            }
            $QbankDO->where = $where; 
            $QbankDO->id = $plaformId;
            $result = $AdminQbankService->qbankList($QbankDO); 

            if ($result->success == TRUE) {
            	$msg['msg'] = $result->message;
                $msg['code'] = $result->code;
                $msg['data'] = $result->data;
                if($result->code==200){
                    $msg['count'] = intval($result->message);
                    $msg['msg'] = "获取成功";
                }
                
            } else {
                $msg['msg'] = "接口获取失败";
            }

        } catch (Exception $ex) {
            $msg['msg'] = $ex->getMessage();
        }
        return json_encode($msg);
    }
    
    /** 
     *  云题库列表 共享题库父级
     *  @param  admin_reg or plaformId
     *  @return JSON [description] 400失败 200成功
     */
    public function sharingList() 
    {
        $msg = ['code'=>400, 'msg'=>'暂无数据', 'data'=>[],'count'=>0];
        $plaformIds = $this->request->param('plaformId') ? $this->request->param('plaformId') : 0; # 平台id
        $liekName = $this->request->param('name') ? $this->request->param('name') : ""; #题库名称 用户名 姓名
        $plaformChildId = $this->request->param('plaformChildId') ? $this->request->param('plaformChildId') : ""; # 赛选平台 不用管这个
        $type = $this->request->param('type') ? $this->request->param('type') : ""; # 共享题库状态 1：未添加 2：已添加 3：待更新 4:已经更新的
        $offset = $this->request->param('offset') ? $this->request->param('offset') : 0; # 分页
        $num = $this->request->param('num') ? $this->request->param('num') : 10; # 条数

        # 获取admin_reg one:获取单个平台admin_reg child:获取当前平台和子平台admin_reg all:超级管理员获取所有平台admin_reg
        $plaformId = $plaformChildId ? $plaformChildId : 0;
        if($plaformId==0){
            $adminReg = getApiAdminReg($plaformId,'all');     
        }else{
            $adminReg = getApiAdminReg($plaformId,'one');
        }
        
        try { 
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $AdminQbankService = new AdminQbankServiceClient(NULL);
            \ApiClient::build($AdminQbankService);
            $QbankDO = new QbankDTO();  
            
            $QbankDO->offset = $offset;
            $QbankDO->num = $num; 
            $QbankDO->filed = "all";
          
            # 总平台查看所有 子平台查看本平台 issharing =1 为共享题库
            $where = " isdelete = 0 and issharing=1 and admin_reg in ('{$adminReg}') ";
            # 模糊查询
            if($liekName){
                $where .=" and (name like '%".$liekName."%' or adminname like '%".$liekName."%' or adminuser like '%".$liekName."%') ";
            }
            # 共享题库状态 赛选状态
            if($type && !empty($type)){
                $QbankDO->userid = $type;
            }

            $QbankDO->where = $where; 
            $QbankDO->id = $plaformIds;
            $result = $AdminQbankService->qbankList($QbankDO); 
            // var_dump($result);exit;
            if ($result->success == TRUE) {
                $msg['msg'] = $result->message;
                $msg['code'] = $result->code;
                $msg['data'] = $result->data; 
                if($result->code==200){
                    $msg['count'] = $result->message;
                    $msg['msg'] = "获取成功";
                }
            } else {
                SLogger::getLogger('qbank_thrift_service', 'thrift_error')->error('error', $result->message);
            }

        } catch (Exception $ex) {
            SLogger::getLogger('qbank_thrift_service', 'thrift_error')->error('thrift call error', $ex);
        }
        return json_encode($msg);
    }

    /** 
     *  添加题库
     *  @param  admin_reg or plaformId
     *  @return JSON [description] 400失败 200成功
     */
    public function addQbank(){
        $msg = ['code'=>400, 'msg'=>'添加题库失败', 'data'=>[]];
        addLog(json_encode($this->request->param()));
        $admin_id = $this->request->param('adminUserId') ? $this->request->param('adminUserId') : 0;
        $admin_reg = $this->request->param('reg') ? $this->request->param('reg') : "";
        $plaformId = $this->request->param('plaform_id') ? $this->request->param('plaform_id') : 0;
        //$sectionList = $this->request->param('section') ? $this->request->param('section') : "";
        $data = $this->request->post();
        $sectionList = json_encode($data['qbank_sections']);
        if(empty($admin_reg)){
            $msg['msg'] = "登录已过期，请重新登录";
           return json_encode($msg);
        }
        $qbankName = html_entity_decode(format_html($data['name']));
        if($qbankName){
            $qbankid = Db::name('qbank')->where(['name'=>$qbankName,'plaformId'=>$plaformId])->field('id')->find();
            if($qbankid){
                $msg['msg'] = "题库名称不可以重复!";
                return json_encode($msg);
            }
        }
        $datas = [
            'plaformId'=>$plaformId, # 平台id 总平台为0
            'adminName'=>$data['adminname'], # 添加人
            'adminUser'=>$data['adminuser'], # 添加账号
            'name'=>$qbankName, # 题库名
            'parentId'=>$data['parentid'], # 上级题库 顶级题库为0
            'status'=>$data['status'], # 禁用启用 
            'issharing'=>$data['issharing'],  # 是否共享
            'remark'=>$data['remark'],  # 秒速
            'createTime'=>time(), # 添加时间
            'updateTime'=>time(), # 修改时间
            'sort'=>$data['sort'], # 排序
            'admin_id'=>1, # 子账号id
            'admin_reg'=>$admin_reg,
            'level'=>1,
            'isdelete'=>0,
            'total'=>0,
            'thumb'=>$data['thumb'],
            'qbankPid'=>0, # 子共享题库的id 添加的时候默认为0自建
            'qbankTag'=>$data['qbank_tag'], #标签
            'qbankTagValue'=>$data['qbank_tag_value'], # 标签分类
            'qbankSections'=>$data['qbank_sections'], # 章节id
            'version'=>1,# 版本号
        ];
        # 总平台 admin_reg
        if($plaformId==0){
            $adminReg = Db::name('admin_user')->where(['id'=>1])->field('reg')->find();
            if($admin_reg!=$adminReg['reg']){
                $msg['msg'] = "请选择正确的平台";
                return json_encode($msg);
            }
        }else{
            $adminReg = getApiAdminReg($plaformId,'one');
            if($adminReg!=$admin_reg){
                $msg['msg'] = "请选择正确的子平台";
               // return json_encode($msg);   
            }
        }

        try{
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $AdminQbankService = new AdminQbankServiceClient(NULL);
            \ApiClient::build($AdminQbankService);
            $QbankDO = new QbankDTO(); 
            $QbankDO->id = $plaformId;
            $QbankDO->data = $datas;
            $QbankDO->filed = $admin_id;
            $QbankDO->where = $admin_reg;
            $QbankDO->update = $sectionList;
            $result = $AdminQbankService->addQbank($QbankDO);
            if($result->success == true){
                $msg['code'] = $result->code;
                $msg['msg'] = $result->message;
                if($result->code==200){
                    $msg['data'] = $result->data[1];
                }
            }

        }catch(Exception $e){
            // $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }

    /**
     * 修改题库
     */
    public function editQbank(){
        $msg = ['code'=>400, 'msg'=>'修改题库失败', 'data'=>[]];
        $admin_reg = $this->request->param('reg') ? $this->request->param('reg') : "";
        $plaformId = $this->request->param('plaformId') ? $this->request->param('plaformId') : 0;
        $qbankId = $this->request->param('qbank_id') ? $this->request->param('qbank_id') : '';
      //  $sectionList = $this->request->param('section') ? $this->request->param('section') : "";
        $data = $this->request->post();
        $sectionList = json_encode($data['qbank_sections']);
        // $sectionList = json_encode([['id'=>156,'name'=>'hha11'],['id'=>157,'name'=>'章节二'],['id'=>158,'name'=>'章节三']]);
        // return $sectionList;
        if(empty($admin_reg)){
            $msg['msg'] = "登录已过期，请重新登录";
           return json_encode($msg);
        }
        if(empty($data) || empty($qbankId)){
            $msg['msg'] = "缺少必要参数";
            return json_encode($msg);
        }
        $qbankName = html_entity_decode($data['name']);
        if($qbankName){
            $qbankid = Db::name('qbank')->where(" id <> {$qbankId} AND name = '{$qbankName}' AND plaformId ={$plaformId} ")->field('id')->find();
            if($qbankid){
                $msg['msg'] = "题库名称不可以重复!";
                return json_encode($msg);
            }
        }
        $datas = [
            'name'=>$qbankName,
            'parentId'=>$data['parentid'],
            'status'=>$data['status'],
            'remark'=>$data['remark'],
            'sort'=>$data['sort'],
            'thumb'=>$data['thumb'],
            'qbankTag'=>$data['qbank_tag'],
            'qbankTagValue'=>$data['qbank_tag_value']
        ];
        if(isset($data['issharing'])){
            $datas['issharing'] = $data['issharing'];
        }

        try{
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $AdminQbankService = new AdminQbankServiceClient(NULL);
            \ApiClient::build($AdminQbankService);
            $QbankDO = new QbankDTO(); 
            $QbankDO->id = $plaformId;
            $QbankDO->data = $datas;
            $QbankDO->userid = $qbankId;
            $QbankDO->where = $admin_reg;
            $QbankDO->update = $sectionList;
            $result = $AdminQbankService->editQbank($QbankDO); 
            if($result->success == true){
                $msg['code'] = $result->code;
                $msg['msg'] = $result->message;
                if($result->code==200){
                    $msg['data'] = $result->data[1];
                }
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }

    /** 
     *  查询题库详情
     *  @param  admin_reg or plaformId
     *  @return JSON [description] 400失败 200成功
     */
    public function qbankInfo(){
        $msg = ['code'=>400, 'msg'=>'暂无题库信息', 'data'=>[]];
        $id =  $this->request->param('qbankid') ? $this->request->param('qbankid') : "";

        if(empty($id)){
            $msg['msg'] = "请带入正确的题库标识";
           return json_encode($msg);
        }

        try{
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $AdminQbankService = new AdminQbankServiceClient(NULL);
            \ApiClient::build($AdminQbankService);
            $QbankDO = new QbankDTO(); 
            $QbankDO->id = $id;
            $result = $AdminQbankService->qbankInfo($QbankDO);
            if($result->success == true){
                $msg['code'] = $result->code;
                $msg['msg'] = $result->message;
                $msg['data'] = $result->data[0];    
                if($result->code==200){ 
                    // var_dump(json_decode($result->data[1]['qbank_tag'],fa));exit;
                    $result->data[1]['qbankTag']= json_decode($result->data[1]['qbankTag'],true);
                    $result->data[1]['qbankTagValue'] = json_decode($result->data[1]['qbankTagValue'],true);
                    $result->data[1]['qbankSections'] = json_decode($result->data[1]['qbankSections'],true);
                    $msg['data'] = $result->data[1];    
                }
            }

        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }
    /**
     * 修改题库状态
     * status 0：禁用 1:启用  2：平台禁用
     */
    public function editStatus(){
        $msg = ['code'=>400, 'msg'=>"题库已操作，请刷新页面", 'data'=>[]];
        $plaformId = $this->request->param('plaformId') ? $this->request->param('plaformId') : 0;
        $admin_reg = $this->request->param('reg') ? $this->request->param('reg') : "";
        $qbankId = $this->request->param('qbank_id') ? $this->request->param('qbank_id') : "";
        $status = $this->request->param('status') ? $this->request->param('status') : "";
        if(empty($admin_reg)){
            $msg['msg'] = "请先登录";
            return json_encode($msg);
        }
        if(empty($qbankId)){
            $msg['msg'] = "缺少必要参数";
            return json_encode($msg);
        }

        try{

            $admin = Db::name("admin_user")->where(['id'=>1])->field('reg')->find();
            $where['id'] = ['in',$qbankId];
            if($plaformId==0||empty($plaformId)){ 
                if($status==0){ # 禁用
                    $upstatus = Db::name('qbank')->where($where)->setField(['status'=>2]);
                }else{ # 启用
                    $upstatus = Db::name('qbank')->where($where)->setField(['status'=>1]);
                } 

            # 子平台修改状态
            }else{
                $where['plaformId'] = $plaformId;
                $where['admin_reg'] = $admin_reg;
                $upstatus = Db::name('qbank')->where($where)->setField(['status'=>$status]);
            }
            if($upstatus){
                $msg['code'] = 200;
                $msg['msg'] = "禁用成功";
                if($status==1){
                    $msg['msg'] = "启用成功";
                }
                
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }

    /**
     * 修改题库是否分享
     *  issharing：0不共享 1共享
     */
    public function editIssharing(){
        $msg = ['code'=>400, 'msg'=>"题库已修改，请刷新页面", 'data'=>[]];
        $plaformId = $this->request->param('parform_id') ? $this->request->param('parform_id') : 0;
        $admin_reg = $this->request->param('reg') ? $this->request->param('reg') : "";
        $qbankId = $this->request->param('qbank_id') ? $this->request->param('qbank_id') : ""; # 123
        $issharing = $this->request->param('issharing') ? $this->request->param('issharing') : ""; #0不 1 共 2平
        if(empty($admin_reg)){
            $msg['msg'] = "请先登录";
            return json_encode($msg);
        }
        if(empty($qbankId) ){
            $msg['msg'] = "缺少必要参数";
            return json_encode($msg);
        }

        try{

            $admin = Db::name("admin_user")->where(['id'=>1])->field('reg')->find();
            $where['id'] = ['in',$qbankId];
            if($plaformId==0 || empty($plaformId)){ 
                if($issharing==0){ # 禁用
                    $upstatus = Db::name('qbank')->where($where)->setField(['issharing'=>2]);
                }else{ # 启用共享
                    $upstatus = Db::name('qbank')->where($where)->setField(['issharing'=>1]);
                } 

            # 子平台修改状态
            }else{
                $where['plaformId'] = $plaformId;
                $where['admin_reg'] = $admin_reg;
                $upstatus = Db::name('qbank')->where($where)->setField(['issharing'=>$issharing]);
            }
            if($upstatus){
                $msg['code'] = 200;
                $msg['msg'] = "设置成功";
                if($status==1){
                    $msg['msg'] = "共享成功";
                }
                
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }
    /**
     * execl 导出题库试题
     * @return [type] [description]
     */
    public function downExecl()
    {  
        ob_end_clean(); # 清空缓冲区
        $msg= ['code'=>400,'data'=>[],'msg'=>''];
        $qbankId = $this->request->param('qbankid') ? $this->request->param('qbankid') :  0;
        $header = ['题型','题干','选项','参考答案','专业解析','知识点','启用状态','题目难度'];
        if(!$qbankId){
            $msg['msg'] = "请带入正确的题库标识";
            return json_encode($msg);
        }
        try {
            $qbankName = Db::name('qbank')->where(['id'=>$qbankId])->field("name")->find();
            $filed = "typeId,question,select,answer,describe,knowsName,status,level";
            $questionsList = Db::name('questions')->where(['qbankId'=>$qbankId,'isdelete'=>0])->field($filed)->select();
            if($questionsList){
                $list = [];
                foreach($questionsList as $v){
                    $list[] = [
                        getTypeId($v['typeId']),
                        deleteHtml($v['question']),
                        deleteHtml($v['select']),
                        deleteHtml($v['answer']),
                        deleteHtml($v['describe']),
                        $v['knowsName'],
                        getStatus($v['status']),
                        getLeve($v['level'])
                    ];
                }
            }else{
                $msg['msg'] = "没有可导出的试题";
                return json_encode($msg);
            }
        } catch (Exception $e) {
            $msg['msg'] = $e->getMessage();
            return json_encode($msg);
        } 
        $name=empty($qbankName['name']) ? '未知' : $qbankName['name'];
        $version = '2007';
        $width = array('B'=>100,'C'=>100,'F'=>50);
        \Excel::oneExport($header, $list, $name, $version,$width);
    }

    /**
     * 继承分享题库
     */
    public function addMyQbank(){
        $msg = ['code'=>400, 'msg'=>'添加到我的题库失败', 'data'=>[]];
        $qbankPid = $this->request->param("qbank_id") ? $this->request->param("qbank_id") :"";
        $adminUserId = $this->request->param("adminUserId") ? $this->request->param("adminUserId") :"";
        $admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg") :"";
        $plaformId = $this->request->param("plaform_id") ? $this->request->param("plaform_id") :0;
        $adminname = $this->request->param("adminname") ? $this->request->param("adminname") :"";
        $adminuser = $this->request->param("adminuser") ? $this->request->param("adminuser") :"";

        if(empty($qbankPid) || empty($admin_reg)  ){
           $msg['msg']  = "缺少必要参数";
           return json_encode($msg);
        }

        try{
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $AdminQbankService = new AdminQbankServiceClient(NULL);
            \ApiClient::build($AdminQbankService);
            $data = ['user'=>$adminuser, 'name'=>$adminname];
            $QbankDO = new QbankDTO(); 
            $QbankDO->id = $plaformId;
            $QbankDO->filed = $admin_reg;
            $QbankDO->gdl_userid = $qbankPid;
            $QbankDO->data = $data;
            $QbankDO->userid = $adminUserId;
            $result = $AdminQbankService->addMyQbank($QbankDO);
            if($result->success == true){
                $msg['msg'] = $result->message;
                $msg['data'] = [];
                $msg['code'] =$result->code;
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }

        return json_encode($msg); 
    }
    /**
     * 更新该题库
     * 有时候我像是着了魔的爱你，一想到你心里便一紧，不再是青春里那个砰砰心跳的心，而是更加坚定的认为我不能和你分离，因为你得到安慰的心。
     */
    public function updateQbank(){
        $msg = ['code'=>400, 'msg'=>'更新题库失败', 'data'=>[]];
        $qbankId = $this->request->param("qbank_id") ? $this->request->param("qbank_id") :""; #分享题库id
        $qbankPid = $this->request->param("qbank_pid") ? $this->request->param("qbank_pid") :""; #被分享题库id
        $admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg") :"";
        $plaformId = $this->request->param("plaform_id") ? $this->request->param("plaform_id") :0;

        try{
            # 如果获取不到需要更新的题库 直接用父亲级别题库加平台加admin_reg查询需要更新的子题库
            if(empty($qbankId)){
                $getQbankId = Db::name('qbank')->where()->filed("id,qbank_pid")->find();
                $qbankId = !empty($getQbankId['id']) ? $getQbankId['id'] : "";
            }
            if(empty($qbankId) || empty($qbankPid) || empty($admin_reg)  ){
                $msg['msg'] = "缺少必要参数";
                return json_encode($msg);
            }

            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $AdminQbankService = new AdminQbankServiceClient(NULL);
            \ApiClient::build($AdminQbankService);
            $data = ['user'=>$adminUser, 'name'=>$adminname];
            $QbankDO = new QbankDTO(); 
            $QbankDO->id = $plaformId;
            $QbankDO->where = $admin_reg;
            $QbankDO->userid = $qbankId;
            $QbankDO->gdl_userid = $qbankPid; 

            $result = $AdminQbankService->updateQbank($QbankDO);
            if($result->success == true){
                $msg['msg'] = $result->message;
                $msg['code'] = $result->code;
            }else{
                $msg['msg'] = "更新失败，接口异常";
            }

        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }

        return json_encode($msg);

    }
    /**
     * 试卷抽题接口
     */
    public function paperQuestions(){
        $msg = ['code'=>400, 'msg'=>'获取失败','data'=>[],'count'=>0];
        $plaformId = $this->request->param("plaformId") ? $this->request->param("plaformId") : "0";
        $qbankId = $this->request->param("qbank_id") ? $this->request->param("qbank_id"):""; # 题库id
        $type = $this->request->param("type") ? $this->request->param("type") : ""; # 试题类型 123456
        $level = $this->request->param("level") ? $this->request->param("level") : "";  # 难易度 123
        $sectionId = $this->request->param("sectionId") ? $this->request->param("sectionId") : 0; #章节id
        $count = $this->request->param('count') ? $this->request->param('count') : 0;

        #$admin_reg = $this->request->param("admin_reg") ? $this->request->param("admin_reg") : "";
        if(empty($qbankId)){
            $msg['msg'] = "请带入正确的题库标识";
            return json_encode($msg);
        }

        try{
            $where = " isdelete=0 and status=1 and qbankId=".$qbankId;
            if(!empty($type) && $type!=0){
                $where .= " and typeId=".$type;
            }
            if(!empty($level) && $level!=0){
                $where.=" and level=".$level;
            }
            if(!empty($sectionId) && $sectionId!=0){
                $where.=" and sectionId=".$sectionId;
            }

            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $AdminQbankService = new AdminQbankServiceClient(NULL);
            \ApiClient::build($AdminQbankService);
            $data = ['user'=>$adminUser, 'name'=>$adminname];
            $QbankDO = new QbankDTO(); 
            $QbankDO->id = $plaformId;
            $QbankDO->where = $where;
            $QbankDO->gdl_userid = $qbankId;
            $QbankDO->userid = $count;

            $result = $AdminQbankService->paperQuestions($QbankDO);
            //var_dump($result);die;
            if($result->success == true){
                if(empty($count) || $count==0){
                    $msg['code'] = $result->code;
                    $msg['msg'] = $result->message;
                    $msg['count'] = $result->data[1]['count'] ? $result->data[1]['count'] : 0;
                }else{
                    $msg['code'] = $result->code;
                    $msg['msg'] = $result->message;
                    $msg['data'] = $result->data;
                    $msg['count'] = count($result->data) ? count($result->data) : 0;
                }    
            }
            
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }
    /**
     * 导出题库列表
     */
    public function downAllQbankExecl(){
        ob_end_clean(); # 清空缓冲区
        $msg = ['code'=>400, 'msg'=>'没有可导出的数据', 'data'=>[],'count'=>0];
        $plaformId = $this->request->param('plaformId') ? $this->request->param('plaformId') : 0; # 平台id
        $liekName = $this->request->param('name') ? $this->request->param('name') : ""; #题库名称
        $plaformChildId = $this->request->param('plaformChildId') ? $this->request->param('plaformChildId') : 0; # 赛选平台
        $sharingPlaform = $this->request->param('sharingPlaform') ? $this->request->param('sharingPlaform') : ""; # 共享题库来源
        $qbankType = $this->request->param('qbankType')>=0 ? $this->request->param('qbankType') : ""; # 题库类型 0：自建题库 1:分享题库
        $status = $this->request->param('status') ? $this->request->param('status') : ""; # 题库状态0:禁用 1：启用 2：平台已禁用 总平台禁用为平台已禁用'
        $sharing  = $this->request->param('sharing') ? $this->request->param('sharing') : "";#是否给下级共享题库 0不共享 1共享 2平台已禁用'
        $adminId = $this->request->param('adminId') ? $this->request->param('adminId') : ""; # 带入管理员is
        $offset = $this->request->param('offset') ? $this->request->param('offset') : 0; # 分页
        $num = $this->request->param('num') ? $this->request->param('num') : 10000000; # 条数

        $selectId = $this->request->param("selectId")?$this->request->param("selectId"):""; # 123逗号分隔
        #利用此条获取题库列表
        $getAllList = $this->request->param('getBankList') ? $this->request->param('getBankList') : ''; 

        # 获取admin_reg one:获取单个平台admin_reg child:获取当前平台和子平台admin_reg all:超级管理员获取所有平台admin_reg
        $plaformId = $plaformChildId ? $plaformChildId : $plaformId;
        if($plaformId==0){
            $adminReg = getApiAdminReg($plaformId,'all');     
        }else{
            $adminReg = getApiAdminReg($plaformId,'child'); 
        }
        
        try { 
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $AdminQbankService = new AdminQbankServiceClient(NULL);
            \ApiClient::build($AdminQbankService);
            $QbankDO = new QbankDTO(); 
            // var_dump($AdminQbankService);exit;
            
            $QbankDO->offset = $offset;
            $QbankDO->num = $num; 
          
            # 总平台查看所有 子平台查看本平台
            $where = " agk_qbank.isdelete = 0 and agk_qbank.admin_reg in ('{$adminReg}') ";
            # 模糊查询
            if($liekName){
                $where .=" and agk_qbank.name like '%".$liekName."%' ";
            }
            # 题库类型 分享
            if($qbankType==1){
                $where .=" and  agk_qbank.qbankPid <>0 ";
            }
            # 自建
            if($qbankType==0 && !empty($qbankType)){
                $where .=" and  agk_qbank.qbankPid=0 ";
            }
            # 题库状态赛选
            if($status && !empty($status)){
                $where .= " and agk_qbank.status = ".$status;
            }
            # 是否为云题库
            if($sharing && !empty($sharing)){
                $where .= " and agk_qbank.issharing = ".$sharing;   
            }
            # 分享题库来源平台
            if($sharingPlaform && !empty($sharingPlaform)){
                // todo
            }
            # 查询该题库是否属于该管理员表
            if($adminId && $adminId!=1){
                $where .=" and uc.adminUserId=".$adminId;
            }
            if($selectId){
                $where.=" and agk_qbank.id in (".$selectId.") ";
            }
            // var_dump($where);die;
            if($getAllList=="all"){
                $QbankDO->update = $getAllList;     
            }
            $QbankDO->where = $where; 
            $QbankDO->id = $plaformId;
            $result = $AdminQbankService->qbankList($QbankDO);
            
            if ($result->code == 200) {
                 $header = ['ID','题库名称','上级题库','更新时间','题目数量','共享题库来源','所属平台','状态','是否共享'];
                $list = [];
                foreach($result->data as $v){
                    $list[]= [
                        $v['id'],
                        $v['name'],
                        $v['parentName'],
                        $v['updateTime'],
                        $v['total'],
                        $v['sharingQbankName'],
                        $v['plaformName']?$v['plaformName']:"未获取",
                        getStatus($v['status']),
                        getIssharing($v['issharing']),
                    ];
                } 
                $version = '2007';
                \Excel::export($header, $list, "题库列表", $version);
            } else {
                $msg['msg'] = "没有可导出的数据";
            }

        } catch (Exception $ex) {
            $msg['msg'] = $ex->getMessage();
        }
        return json_encode($msg);
    }
    /**
     * 下载共享题库
     */
    public function downIsharingExecl(){
        ob_end_clean(); # 清空缓冲区
        $msg = ['code'=>400, 'msg'=>'暂无数据', 'data'=>[],'count'=>0];
        $plaformIds = $this->request->param('plaformId') ? $this->request->param('plaformId') : 0; # 平台id
        $liekName = $this->request->param('name') ? $this->request->param('name') : ""; #题库名称 用户名 姓名
        $plaformChildId = $this->request->param('plaformChildId') ? $this->request->param('plaformChildId') : ""; # 赛选平台 不用管这个
        $type = $this->request->param('type') ? $this->request->param('type') : ""; # 共享题库状态 1：未添加 2：已添加 3：待更新 4:已经更新的
        $offset = $this->request->param('offset') ? $this->request->param('offset') : 0; # 分页
        $num = $this->request->param('num') ? $this->request->param('num') : 1000000; # 条数
        
        $selectId = $this->request->param("selectId")?$this->request->param("selectId"):""; # 123逗号分隔
        # 获取admin_reg one:获取单个平台admin_reg child:获取当前平台和子平台admin_reg all:超级管理员获取所有平台admin_reg
        $plaformId = $plaformChildId ? $plaformChildId : 0;
        if($plaformId==0){
            $adminReg = getApiAdminReg($plaformId,'all');     
        }else{
            $adminReg = getApiAdminReg($plaformId,'one');
        }
        
        try { 
            \ApiClient::init(Config::get('api.appid'), Config::get('api.secret'), 30, array('gdlApiSdk','gdlCloudSdk'));
            $AdminQbankService = new AdminQbankServiceClient(NULL);
            \ApiClient::build($AdminQbankService);
            $QbankDO = new QbankDTO();  
            
            $QbankDO->offset = $offset;
            $QbankDO->num = $num; 
            $QbankDO->filed = "all";
          
            # 总平台查看所有 子平台查看本平台 issharing =1 为共享题库
            $where = " isdelete = 0 and issharing=1 and admin_reg in ('{$adminReg}') ";
            # 模糊查询
            if($liekName){
                $where .=" and (name like '%".$liekName."%' or adminname like '%".$liekName."%' or adminuser like '%".$liekName."%') ";
            }
            # 共享题库状态 赛选状态
            if($type && !empty($type)){
                $QbankDO->userid = $type;
            }
            if($selectId){
                $where.=" and agk_qbank.id in (".$selectId.") ";
            }

            $QbankDO->where = $where; 
            $QbankDO->id = $plaformIds;
            $result = $AdminQbankService->qbankList($QbankDO);  
            if ($result->code == 200) {
                 $header = ['ID','云题库名称','上级题库','更新时间','题目数量','共享题库来源','所属平台','是否共享','云题库状态'];
                $list = [];
                foreach($result->data as $v){
                    $list[]= [
                        $v['id'],
                        $v['name'],
                        $v['parentName'],
                        $v['updateTime'],
                        $v['total'],
                        $v['sharingQbankName'],
                        $v['plaformName']?$v['plaformName']:"未获取",
                        getIssharing($v['issharing']),
                        getStatus($v['status'])
                    ];
                }
                $version = '2007';
                \Excel::export($header, $list, "云题库列表", $version);
            } else {
                $msg['msg'] = "暂无数据下载";
            }

        } catch (Exception $ex) {
            SLogger::getLogger('qbank_thrift_service', 'thrift_error')->error('thrift call error', $ex);
        }
        return json_encode($msg);
    }
    
     
    /**
     * 删除题库
     */
    public function deleteQbank(){
        $msg = ['code'=>400, 'msg'=>"删除失败", 'data'=>[]];
        $plaformId = $this->request->param('parform_id') ? $this->request->param('parform_id') : 0;
        $admin_reg = $this->request->param('reg') ? $this->request->param('reg') : "";
        $id = $this->request->param('id') ? $this->request->param('id') : "";
        $delete = $this->request->param('delete') ? $this->request->param('delete') : "1";
       
        if(empty($id) || empty($delete)){
            $msg['msg'] = "缺少必要参数";
            return json_encode($msg);
        } 
        try{ 
            #查询该题库是否已生成试卷
            $paperWhere['dbs'] = ['in',$id];
            $paperList = Db::name('paper')->where($paperWhere)->field('id')->select();
            if($paperList){
                $msg['msg'] = "删除的题库包含已生成的试卷，请先彻底删除相关试卷";
                return json_encode($msg);
            }

            $where['id'] = ['in',$id];
            $upstatus = Db::name('qbank')->where($where)->setField(['isdelete'=>$delete]); 
            if($upstatus){
                # 继续删除该题库下试题
                $quesWhere['qbankId'] = ['in',$id];
                $quesRes = Db::name('questions')->where($quesWhere)->setField(['isdelete'=>$delete]);
                $msg['code'] = 200;
                $msg['msg'] = "已删除";
            }
        }catch(Exception $e){
            $msg['msg'] = $e->getMessage();
        }
        return json_encode($msg);
    }


    public function emptyQbank(){
        $msg = ['code'=>400, 'msg'=>"清空失败", 'data'=>[]];
        $plaformId = $this->request->param('parform_id') ? $this->request->param('parform_id') : 0;
        $admin_reg = $this->request->param('reg') ? $this->request->param('reg') : "";
        $id = $this->request->param('id') ? $this->request->param('id') : "";//题库ID
        $delete = $this->request->param('delete') ? $this->request->param('delete') : "1";

        if(empty($id) || empty($delete)){
            $msg['msg'] = "缺少必要参数";
            return json_encode($msg);
        }
        try{
            // $paperWhere['dbs'] = ['in',$id];
            // $paperList = Db::name('paper')->where($paperWhere)->field('id')->select();
            // if($paperList){
            //     $msg['msg'] = "清空的题库包含已生成的试卷，请先彻底删除相关试卷";
            //     return json_encode($msg);
            // }

            # 继续删除该题库下试题
            $quesWhere['qbankId'] = ['in',$id];
            $quesRes = Db::name('questions')->where($quesWhere)->setField(['isdelete'=>$delete]);
            if($quesRes){
                $ques = Db::table('agk_questions')->where(['status' => 1, 'isdelete' => 0,'qbankId'=>$id])->field('count(*) as num')->find();
                if (empty($ques['num'])) $ques['num'] = 0; 
                # 修改题库题目数量
                Db::table('agk_qbank')->where('id', $id)->update(['total' => $ques['num']]);
            }
            $msg['code'] = 200;
            $msg['msg'] = "已清空";
        }catch(Exception $e){
            $msg['msg'] = "清空失败";
        }
        return json_encode($msg);
    }
}